package com.fubowen.lepton.helper

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.room.Room
import com.fubowen.lepton.conf.LeptonDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext


object DBHelper {

    private lateinit var instance: LeptonDatabase
    private lateinit var dataStore: DataStore<Preferences>
    val db: LeptonDatabase get() = instance

    fun init(context: Context, store: DataStore<Preferences>) {
        instance = Room
            .databaseBuilder(context, LeptonDatabase::class.java, "lepton-db")
            .allowMainThreadQueries()
            .fallbackToDestructiveMigration()
            .build()
        dataStore = store
    }

    fun get(key: String) =
        dataStore.data.map { preferences -> preferences[stringPreferencesKey(key)] }

    fun get(key: Int) =
        dataStore.data.map { preferences -> preferences[stringPreferencesKey(key.toString())] }

    suspend fun set(key: String, value: String) = withContext(Dispatchers.IO) {
        dataStore.edit { settings ->
            settings[stringPreferencesKey(key)] = value
        }
    }

    suspend fun set(key: Int, value: String) = withContext(Dispatchers.IO) {
        dataStore.edit { settings ->
            settings[stringPreferencesKey(key.toString())] = value
        }
    }

    suspend fun set(key: Int, value: Int) = withContext(Dispatchers.IO) {
        dataStore.edit { settings ->
            settings[stringPreferencesKey(key.toString())] = value.toString()
        }
    }
}